#!/usr/bin/python
# -*- coding: UTF-8 -*-


# 自动登录，沿用之前的老办法，通过chrome来登录天猫超市

import os
from selenium import webdriver
import time

# 引入等待
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 安装APScheduler，这是一个定时框架
# from apscheduler.schedulers.blocking import BlockingScheduler

# 环境配置
chromedriver = "C:\Program Files (x86)\Google\Chrome\Application"
os.environ["webdriver.ie.driver"] = chromedriver
driver = webdriver.Chrome()  # 选择Chrome浏览器

# 账号密码配置
username = "sunday296"  # 用户名
password = "qici33ep"  # 密码

# 茅台地址
MouTai_url = r'https://chaoshi.detail.tmall.com/item.htm?spm=a3204.17709488.5400028360.1.454cc6c0YF3hTm&id=20739895092'
# MouTai_url =r'https://detail.tmall.com/item.htm?id=545421172623&spm=875.7931836/B.2017077.4.2f2a4265QiyAUO&scm=1007.12144.81309.73263_0_0&pvid=aa888c87-ea74-4405-9014-2edef6aa82c8&utparam=%7B%22x_hestia_source%22:%2273263%22,%22x_object_type%22:%22item%22,%22x_hestia_subsource%22:%22default%22,%22x_mt%22:8,%22x_src%22:%2273263%22,%22x_pos%22:3,%22wh_pid%22:-1,%22x_pvid%22:%22aa888c87-ea74-4405-9014-2edef6aa82c8%22,%22scm%22:%221007.12144.81309.73263_0_0%22,%22x_object_id%22:545421172623,%22tpp_buckets%22:%222144#0#81309#0%22%7D'

# 登录
def login():
    # 打开登录界面
    driver.get(
        'https://login.tmall.com/?spm=875.7931836/B.a2226mz.1.54034265e2udqt&redirectURL=https%3A%2F%2Fwww.tmall.com%2F%3Fali_trackid%3D2%3Amm_26632258_3504122_48284354%3A1608700065_111_1732362246%26union_lens%3DlensId%3A0b0bad7d_0cce_16d38f83951_49a9%3Brecoveryid%3A1608700065_111_1732362246%26clk1%3Db5c6e9b594f9d0ef0f3bf49ed380988f%26bxsign%3DtbkDLXF%2FrTqt0RzcPy5aS4bKNKJDprEDQgEdBKWUSMWSgYNkkT20zhpcbgpW9F8Squxz%2BFBdgSqhWZOltirpwr2Z0cxTCsYd3GYixtlcOvuMQc%3D')
    driver.maximize_window()
    time.sleep(5)

    # 因为登录框在另一个frame中，先定位到frame
    driver.switch_to.frame('J_loginIframe')

    driver.find_element_by_id('fm-login-id').click()  # 点击用户名输入框
    driver.find_element_by_id('fm-login-id').clear()  # 清空输入框
    driver.find_element_by_id('fm-login-id').send_keys(username)  # 自动敲入用户名

    driver.find_element_by_id('fm-login-password').click()  # 点击密码输入框
    driver.find_element_by_id('fm-login-password').clear()  # 清空输入框
    driver.find_element_by_id('fm-login-password').send_keys(password)  # 自动敲入密码

    # driver.find_element_by_class_name('fm-button fm-submit password-login').click()  # 点击“登录”按钮
    # 不知道为啥，这个登录不了，换成上层classname
    driver.find_element_by_class_name('fm-btn').click()  # 点击“登录”按钮

    print('login is done')


def oye():
    # moutai购买界面的时间倒计时跟电脑时间好像差了一两秒，随后再说
    # print('yes')
    driver.get(MouTai_url)
    # 选择购买项目
    # 这里要加一个unitl相关
    # moutai版本,没有wait，但已经测试没问题
    """
    driver.find_element_by_class_name('tm-relate-current').click()
    #moutai颜色分类,实在定位不到，只能用xpath的绝对路径了
    driver.find_element_by_xpath('//*[@id="J_DetailMeta"]/div[1]/div[1]/div/div[4]/div/div/dl[2]/dd/ul/li/a').click()
    #数量增加一个
    driver.find_element_by_class_name('mui-amount-increase').click()
    """
    # 添加wait，moutai版本1
    """
    wait = WebDriverWait(driver, 10, 0.1)
    while 1:
        print('一层循环开始')
        button1 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "tm-relate-current")))
        button1.click()
        print('button1 is done')
        button2 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//*[@id='J_DetailMeta']/div[1]/div[1]/div/div[4]/div/div/dl[2]/dd/ul/li/a")))
        button2.click()
        print('button2 is done')
        button3 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "mui-amount-increase")))
        button3.click()
        print('button3 is done')

        while 1:
            print('二层循环开始')
            try:
                button4 = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "立即购买")))
                button4.click()
                print('button4 is done')
            except Exception:
                driver.refresh()
                print('refresh is done')
            else:
                print("立即购买完毕")
                break
        driver.switch_to.window(driver.window_handles[-1])
        button5 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "go-btn")))
        button5.click()
        print("提交订单完毕")
    """
    # 添加wait，moutai版本2
    #"""
    wait = WebDriverWait(driver, 10, 0.01)
    button1 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "tm-relate-current")))
    button1.click()
    print('button1 is done')
    button2 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//*[@id='J_DetailMeta']/div[1]/div[1]/div/div[4]/div/div/dl[2]/dd/ul/li/a")))
    button2.click()
    print('button2 is done')
    button3 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "mui-amount-increase")))
    button3.click()
    print('button3 is done')

    buy_wait = WebDriverWait(driver, 600, 0.01)#这里设置了3个小时，超出3个小时会报错
    #button4 = buy_wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "立即购买")))
    button4 = buy_wait.until(EC.element_to_be_clickable((By.ID, "J_LinkBuy")))
    button4.click()
    print('button4 is done')
    print("立即购买完毕")

    driver.switch_to.window(driver.window_handles[-1])
    button5 = buy_wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "go-btn")))
    button5.click()
    print("提交订单完毕")
    #"""


    # 其他商品，测试购买流程，测试完成
    """
    wait = WebDriverWait(driver, 10, 0.1)
    button1 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//*[@id='J_DetailMeta']/div[1]/div[1]/div/div[4]/div/div/dl[1]/dd/ul/li[7]/a/span")))
    button1.click()
    print('button1 is done')
    button2 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//*[@id='J_DetailMeta']/div[1]/div[1]/div/div[4]/div/div/dl[2]/dd/ul/li[13]/a/span")))
    button2.click()
    print('button2 is done')
    button3 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "//*[@id='J_Amount']/span[1]/span[1]/span[1]")))
    button3.click()
    print('button3 is done')
    button4 = wait.until(EC.element_to_be_clickable((By.ID, "J_LinkBuy")))
    button4.click()
    print('button4 is done')
    print("立即购买完毕")
    driver.switch_to.window(driver.window_handles[-1])
    button5 = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "go-btn")))
    button5.click()
    print("提交订单完毕")
    time.sleep(20)
    """
    """
    driver.find_element_by_xpath('//*[@id="J_DetailMeta"]/div[1]/div[1]/div/div[4]/div/div/dl[1]/dd/ul/li[7]/a/span').click()
    driver.find_element_by_xpath('//*[@id="J_DetailMeta"]/div[1]/div[1]/div/div[4]/div/div/dl[2]/dd/ul/li[13]/a/span').click()
    driver.find_element_by_xpath('//*[@id="J_Amount"]/span[1]/span[1]/span[1]').click()
    
    #购买
    # 这里要加一个unitl相关
    driver.find_element_by_link_text('立即购买').click()
    print('点击购买完毕')
    """
    """
    #这里要需要判断一下跳转网页情况，有点难
    # 这里要加一个unitl相关
    time.sleep(10)
    #切入新界面，window_handles[-1]应该可以改成current_window_handle，随后再试
    driver.switch_to.window(driver.window_handles[-1])
    #new_url = driver.current_url
    #driver.get(new_url)
    driver.find_element_by_class_name('go-btn').click()
    time.sleep(50)
    """
    """
    #获取点击立即购买后的句柄，不能用句柄，句柄是新窗口
    handles = driver.window_handles
    handles1 = driver.current_window_handle
    print(handles)
    print(handles1)
    #进入新的窗口
    for handle in handles:
        if handle != current_handle:
            driver.switch_to.window(handle)
            print('跳转到提交订单页面')
            #点击提交订单
            driver.find_element_by_class_name('go-btn').click()
            time.sleep(10)
    """


def main():
    login()
    oye()


if __name__ == '__main__':
    main()

# driver.navigate().refresh()网页刷新
# 加入购物车id = J_LinkBasket
